import config from 'config';
import CryptoJS from 'crypto-js';
const secretKey = config.get<string>('secretKey'); // 生成一个随机的32字节密钥  

export class CryptoHelper {
  key: any;
  iv = CryptoJS.lib.WordArray.create([
    21,
    0,
    13,
    179,
    150,
    169,
    186,
    178,
    89,
    44,
    17,
    10,
    31,
    174,
    141,
    78
  ]);
  constructor(key = secretKey) {
    this.key = key;
  }

  encrypt(data: string) {
    if (!this.key) {
      throw new Error('Key has not been imported.');
    }
    const cipherParams = CryptoJS.AES.encrypt(
      data,
      this.key,
      {
        mode: CryptoJS.mode.CBC,
        padding: CryptoJS.pad.Pkcs7,
        iv: this.iv
      }
    );
    return cipherParams.toString(); // 返回Base64编码的密文  
  }

  decrypt(encryptedData: string) {
    if (!this.key) {
      throw new Error('Key has not been imported.');
    }
    const bytes = CryptoJS.AES.decrypt(
      encryptedData,
      this.key, {
      mode: CryptoJS.mode.CBC,
      padding: CryptoJS.pad.Pkcs7,
      iv: this.iv
    }
    );
    return bytes.toString(CryptoJS.enc.Utf8); // 返回解密后的明文  
  }
}
export const cryptoHelper = new CryptoHelper();
export const cryptoHelper2 = new CryptoHelper('fb69b8d3aa51f32ad0c82ec5a3e188e4');
// 使用示例  


// const plaintext = 'hello';
// const encryptedText = cryptoHelper.encrypt(plaintext);
// console.log('Encrypted:', encryptedText);
// const decryptedText = cryptoHelper.decrypt(encryptedText);
// console.log('Decrypted:', decryptedText);
